package com.example.myapplication;

import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
;


import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;

import org.litepal.crud.DataSupport;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import jxl.read.biff.BiffException;
import jxl.write.WriteException;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener, View.OnClickListener {

    private Spinner spn_point;
    private Spinner spn_address;
    private TextView tv_point_name;
    private TextView tv_address_details;
    private ListView lv_content;
    private Button btn_modify;
    private Button btn_export;
    private EditText edit_address;
    private EditText edit_address_details;
    private LinearLayout ll_address;
    private static final String TAG = "MainActivity";
    private List<String> list0 = new ArrayList<>();
    private List<String> list2 = new ArrayList<>();
    private List<Investigation> list;

    private SharedPreferences sharedPreferences;
    private String excelName;
    private InvestigationAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获取sharePreferences中的地区编码
        sharedPreferences = getSharedPreferences("myData", MODE_PRIVATE);
        excelName = sharedPreferences.getString("excelName", "");
        initView();
        initEvent();
        try {
            initData();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (BiffException e) {
            e.printStackTrace();
        }
        spn_point.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, list0));
        spn_point.setOnItemSelectedListener(this);
        spn_address.setOnItemSelectedListener(this);
    }


    private void initView() {
        spn_point = (Spinner) findViewById(R.id.spn_point);
        spn_address = (Spinner) findViewById(R.id.spn_address);
        tv_point_name = (TextView) findViewById(R.id.tv_point_name);
        tv_address_details = (TextView) findViewById(R.id.tv_address_details);
        lv_content = (ListView) findViewById(R.id.lv_content);
        btn_modify = (Button) findViewById(R.id.btn_modify);
        btn_export = (Button) findViewById(R.id.btn_export);
        edit_address = (EditText) findViewById(R.id.edit_address);
        edit_address_details = (EditText) findViewById(R.id.edit_address_details);

        ll_address = (LinearLayout) findViewById(R.id.ll_address);
    }

    private void initEvent() {
        btn_modify.setOnClickListener(this);
        btn_export.setOnClickListener(this);
    }

    /*初始化界面数据*/
    private void initData() throws IOException, BiffException {
        Cursor c1 = DataSupport.findBySQL("select distinct point from Investigation");
        if (c1.moveToFirst()) {
            do {
                list0.add(c1.getString(c1.getColumnIndex("point")));
            } while (c1.moveToNext());
        }
        c1.close();

    }


    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId()) {
            case R.id.spn_point:
                list2.clear();
                Cursor c1 = DataSupport.findBySQL("select distinct address,pointname from Investigation where point = ?", spn_point.getSelectedItem().toString());
                if (c1.moveToFirst()) {
                    tv_point_name.setText(c1.getString(c1.getColumnIndex("pointname")));
                    do {
                        list2.add(c1.getString(c1.getColumnIndex("address")));
                    } while (c1.moveToNext());
                }
                c1.close();
                spn_address.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, list2));
                break;
            case R.id.spn_address:
                list = DataSupport.where("point = ? and address = ?", spn_point.getSelectedItem().toString(), spn_address.getSelectedItem().toString()).find(Investigation.class);
                if (list.get(0).getRandom().equals("1")) {
                    ll_address.setVisibility(View.VISIBLE);
                    tv_address_details.setVisibility(View.GONE);
                    edit_address_details.setVisibility(View.VISIBLE);
                }
                tv_address_details.setText(list.get(0).getAddressDetails());
                list.clear();
                list = DataSupport.where("point = ? and address = ?", spn_point.getSelectedItem().toString(), spn_address.getSelectedItem().toString()).find(Investigation.class);
                adapter = new InvestigationAdapter(this, R.layout.item_content, list);
                lv_content.setAdapter(adapter);
                edit_address_details.setText(tv_address_details.getText().toString());
                edit_address.setText(spn_address.getSelectedItem().toString());
                break;
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_modify:
                //更新数据库
                Investigation investigation = new Investigation();
                investigation.setAddress(edit_address.getText().toString());
                investigation.setAddressDetails(edit_address_details.getText().toString());
                investigation.updateAll("point = ? and address = ?", spn_point.getSelectedItem().toString(), spn_address.getSelectedItem().toString());
                list = DataSupport.where("point = ? and address = ?", spn_point.getSelectedItem().toString(), edit_address.getText().toString()).find(Investigation.class);
                int position = spn_address.getSelectedItemPosition();
                list2.clear();
                Cursor c1 = DataSupport.findBySQL("select distinct address,pointname from Investigation where point = ?", spn_point.getSelectedItem().toString());
                if (c1.moveToFirst()) {
                    tv_point_name.setText(c1.getString(c1.getColumnIndex("pointname")));
                    do {
                        list2.add(c1.getString(c1.getColumnIndex("address")));
                    } while (c1.moveToNext());
                }
                c1.close();
                spn_address.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, list2));
                spn_address.setSelection(position);
                Toast.makeText(MainActivity.this, "校验成功", Toast.LENGTH_SHORT).show();
                break;
            case R.id.btn_export:
                List<Investigation> resultList = DataSupport.findAll(Investigation.class);
                try {
                    boolean success = ExcelUtils.writeExcel(excelName, resultList);
                    if (success) {
                        Toast.makeText(MainActivity.this, "成功导出在" + excelName + "文件夹下", Toast.LENGTH_SHORT).show();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (WriteException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 0 && resultCode == 0) {

            adapter.notifyDataSetChanged();

        } else {
            ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
            Log.d(TAG, images.get(0).name);
        }
    }

    private int getPictureNum(String point, String address, String standard, String code, String thirdIndex) {
        List<Investigation> investigations = DataSupport.select("picture")
                .where("point = ? and address = ? and standard = ? and code = ? and thirdIndex = ?", point, address, standard, code, thirdIndex)
                .find(Investigation.class);

        String.valueOf(investigations.get(0).getPicture());
        String pictures = investigations.get(0).getPicture();
        String myString = new String(pictures);
        Log.d("mymString", myString);
        int start = 0;
        int num = 0;
        //获取图片名串中的图片数量
        while (start != pictures.length()) {
            myString = myString.substring(start);
            Log.d("mymmString", myString);
            Log.d("myStart", String.valueOf(start));
            PhotoInfo photoInfo = new PhotoInfo();
            photoInfo.setChecked(false);
            /*String photoName="";*/
            Log.d("myString,", String.valueOf(myString.indexOf("/r/n")));
            if (myString.indexOf("/r/n") < 0) break;
            /*photoName=myString.substring(0,myString.indexOf("/r/n"));*/
            /*Log.d("myPhotoName",photoName);*/
            num++;
           /* photoInfo.setUrl(Environment.getExternalStorageDirectory()
                    .toString() + "/"+areaCode+"/"+photoName);
            mGridAdapter.getList().add(photoInfo);*/
            start = myString.indexOf("/r/n") + 4;
        }
        return num;
    }
}

